import { watch } from 'vue'
import { useDebounceFn } from '@vueuse/core'
import { useCanvasStore, useElementStore } from '@/store'
import { saveToStorage, loadFromStorage } from '@/utils/storageHelper'

// 自动保存（防抖1秒，避免频繁读写）
export const useAutoSave = () => {
  const canvasStore = useCanvasStore()
  const elementStore = useElementStore()

  // 防抖保存函数（1秒内多次变化只执行一次）
  const debouncedSave = useDebounceFn(async () => {
    const saveData = {
      elements: elementStore.elements,
      canvasState: {
        panX: canvasStore.panX,
        panY: canvasStore.panY,
        zoom: canvasStore.zoom
      }
    }
    await saveToStorage(saveData)
  }, 1000)

  // 监听元素或画布状态变化，触发保存
  watch(
    [() => elementStore.elements, () => canvasStore.$state],
    debouncedSave,
    { deep: true } // 深度监听对象内部变化
  )

  return { debouncedSave }
}

// 加载存储数据并同步到Store
export const useLoadStorage = async () => {
  const canvasStore = useCanvasStore()
  const elementStore = useElementStore()

  const storedData = await loadFromStorage()
  if (storedData) {
    // 同步元素数据
    elementStore.elements = storedData.elements
    // 同步画布状态
    canvasStore.updateCanvasState(storedData.canvasState)
  }
  return storedData
}